package com.ynet.middleground.mobile.approve.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import com.google.common.base.Throwables;
import com.ynet.core.exception.BusinessException;
import com.ynet.core.log.IfpLogger;
import com.ynet.middleground.mobile.approve.commom.ResponseResult;
import com.ynet.middleground.mobile.approve.constant.ErrorMessageConstant;
import com.ynet.middleground.mobile.approve.request.FileOperateReq;
import com.ynet.middleground.mobile.approve.service.FileCenterService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * @ClassName FileController
 * @Description 文件相关Controller
 * @Author liwq
 * @Date 2021/3/28 19:01
 * @Version 1.0
 */
@CrossOrigin("*")
@RestController
@RequestMapping("/")
@Api(value = "文件处理相关服务", tags = "文件处理相关服务")
public class FileController {

    @Autowired
    private FileCenterService fileCenterService;

    /**
     * 删除上传附件
     * 
     * @param req 文件相对路径 例：zhongtai/李文全测试-1617009833612.txt
     * @return
     */
    @PostMapping("/file/delete")
    @ApiOperation(value = "删除上传附件", notes = "删除上传附件")
    public ResponseResult<String> fileDelete(@RequestBody @Valid FileOperateReq req) {
        IfpLogger.info(Thread.currentThread().getStackTrace()[1].getMethodName(), "删除上传附件,reqParams: {}",
            req.toString());
        ResponseResult<String> responseResult = new ResponseResult<>();
        try {
            responseResult = fileCenterService.fileDelete(req.getFileUrl());
        } catch (BusinessException e) {
            responseResult.setError(e.getCode(), e.getMessage());
        } catch (Exception e) {
            IfpLogger.error(Thread.currentThread().getStackTrace()[1].getMethodName(), "删除上传附件服务异常, case: {}",
                Throwables.getStackTraceAsString(e));
            responseResult.setError(ErrorMessageConstant.ECUC0018_CODE, ErrorMessageConstant.ECUC0018_MESSAGE);
        }
        return responseResult;
    }

    /**
     * 文件上传
     * 
     * @param file
     * @param fileName
     * @param fileExt
     * @return 文件相对路径
     */
    @PostMapping("/file/upload")
    @ApiOperation(value = "文件上传 (form 表单提交)", notes = "文件上传 (form 表单提交)")
    @ApiImplicitParams({@ApiImplicitParam(name = "file", value = "文件", dataType = "__file", paramType = "form"),
        @ApiImplicitParam(name = "fileName", value = "文件名", dataType = "String", paramType = "form"),
        @ApiImplicitParam(name = "fileExt", value = "文件后缀", dataType = "String", paramType = "form")})
    public ResponseResult<String> fileUpload(@RequestParam("file") MultipartFile file,
        @RequestParam("fileName") String fileName, @RequestParam("fileExt") String fileExt) {
        IfpLogger.info(Thread.currentThread().getStackTrace()[1].getMethodName(), "文件上传,reqParams: {}",
            file.toString());
        ResponseResult<String> responseResult = new ResponseResult<>();
        try {
            responseResult = fileCenterService.fileUpload(file, fileName, fileExt);
        } catch (BusinessException e) {
            responseResult.setError(e.getCode(), e.getMessage());
        } catch (Exception e) {
            IfpLogger.error(Thread.currentThread().getStackTrace()[1].getMethodName(), "文件上传服务异常, case: {}",
                Throwables.getStackTraceAsString(e));
            responseResult.setError(ErrorMessageConstant.ECUC0014_CODE, ErrorMessageConstant.ECUC0014_MESSAGE);
        }
        return responseResult;
    }

    /**
     * 文件下载
     * 
     * @param req 文件相对路径，例：zhongtai/李文全测试-1617009833612.txt
     * @return
     */
    @GetMapping("/file/get")
    @ApiOperation(value = "文件下载 (浏览器会触发下载)", notes = "文件下载 (浏览器会触发下载)")
    @ApiImplicitParam(value = "文件短路径地址", name = "fileUrl", dataType = "String", paramType = "query")
    public void fileDownLoad(HttpServletRequest req, HttpServletResponse res) throws IOException {
        // IfpLogger.info(Thread.currentThread().getStackTrace()[1].getMethodName(), "文件下载,reqParams: {}",
        // req.toString());
        String fileUrl = req.getParameter("fileUrl");
        IfpLogger.info(Thread.currentThread().getStackTrace()[1].getMethodName(), "文件下载,fileUrl: {}", fileUrl);
        if (StringUtils.isEmpty(fileUrl)) {
            throw new BusinessException(ErrorMessageConstant.ECUC0016_MESSAGE, ErrorMessageConstant.ECUC0016_CODE);
        }
        fileCenterService.fileDownLoad(fileUrl, res);
    }

}
